package logic

import (
	"context"
	"errors"
	"video-system/model/cache"
	"video-system/model/mysql"

	"video-system/userrpc/internal/svc"
	"video-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
	return &ResetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 重置密码
func (l *ResetPasswordLogic) ResetPassword(in *userrpc.ResetPasswordRequest) (*userrpc.ResetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.UserInfo

	if err := findUser.FindUserByPhoneNum(mysql.DB, in.PhoneNum); err != nil {
		return nil, err
	}

	if findUser.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.PhoneNum).Result()

	if result != in.SmsCode {
		return nil, errors.New("验证码错误,请重新输入")
	}

	if in.NewPwd != in.Pwd {
		return nil, errors.New("两次密码输入不一致,请更改")
	}

	if in.Pwd == findUser.Pwd {
		return nil, errors.New("新密码与旧密码一致,请重新输入")
	}

	findUser.Pwd = in.Pwd

	err := findUser.UpdatePassword(mysql.DB)
	if err != nil {
		return nil, errors.New("修改失败")
	}

	return &userrpc.ResetPasswordResponse{
		UserId: int64(findUser.ID),
	}, nil
}
